<template>
	<div class="category_container">
		<div class="category_header">
			<el-input placeholder="请输入类目ID" v-model="searList.id" clearable style="width: 200px;"></el-input>
			<el-input placeholder="请输入类目名称" v-model="searList.title" clearable style="width: 200px;"></el-input>
			<el-select v-model="searList.level" style="width: 200px" placeholder="请选择类目级别">
				<el-option v-for="(item,index) in categoryLevel" :key="index" :label="item.name" :value="item.value" />
			</el-select>
			<el-cascader :options="options" :props="{ checkStrictly: true }" v-model="parentTree" clearable
				placeholder="请选择父类目" filterable @change="handleLink" />
			<el-button type="primary" icon="el-icon-search" style="margin-left: 5px;" @click='search()'>查找</el-button>
			<el-button type="primary" icon="el-icon-edit" @click="fixCategory('add')">添加</el-button>
		</div>
		<el-table v-loading="loading" :data="categoryList" size="small" element-loading-text="正在查询中。。。" border fit
			highlight-current-row>
			<el-table-column label="类目ID" align="center" prop="value" />
			<el-table-column label="类目名" align="center">
				<template slot-scope="scope">
					<el-tag>{{scope.row.label}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="全类目名" align="center">
				<template slot-scope="scope">
					<el-tag>{{scope.row.fullName}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="父类目ID" align="center" prop="parent" />
			<el-table-column label="级别" align="center">
				<template slot-scope="scope">
					<el-tag>{{filltterLevel(scope.row.level)}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="标志图片" align="center" />
			<el-table-column label="类目图片" align="center">
				<template slot-scope="scope">
					<img :src="scope.row.picUrl" width="80" />
				</template>
			</el-table-column>
			<el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button type="primary" size="mini" @click="fixCategory('edit',scope.row)">编辑</el-button>
					<el-button type="danger" size="mini" @click='deleteCategory(scope.row)'>删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 添加或编辑 -->
		<el-dialog :visible.sync="dialogVisible" :title="title">
			<el-form ref="categoryForm" :rules="rules" :model="categoryForm" status-icon label-position="left"
				label-width="100px" style="width: 400px; margin-left:50px;">
				<el-form-item label="类目名称" prop="title">
					<el-input v-model="categoryForm.title" />
				</el-form-item>
				<el-form-item label="类目图片" prop="picUrl">
					<el-upload :action="uploadPath" :show-file-list="false" :on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload" class="avatar-uploader">
						<img v-if="categoryForm.picUrl" :src="categoryForm.picUrl" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="父类目">
					<el-cascader :options="options" :props="{ checkStrictly: true }" v-model="categoryId"
						placeholder="关联父类目、默认一级类目" clearable filterable @change="handleLink2" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeDialog()">取消</el-button>
				<el-button v-if="title === '创建'" type="primary" @click="createCategory('categoryForm')">确定</el-button>
				<el-button v-else type="primary" @click="updateData('categoryForm')">确定</el-button>
			</div>
		</el-dialog>
		<!-- 分页 -->
		<el-footer v-if="categoryList.length>0" class="border-top d-flex align-items-center px-0  bg-white"
			style="margin-top: 36px;">
			<div style="flex: 1;" class="px-2">
				<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page.sync="searList.pageNo" :page-sizes="[10, 20, 30, 50, 100]" :page-size="searList.limit"
					layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</el-footer>
	</div>
</template>

<script>
	import {
		getCategoryList,
		getCategoryTree,
		getcategorySecondTree,
		deleteCategory,
		addCategory,
		uploadPath,
		updateCategory
	} from "../api.js"
	export default {
		data() {
			return {
				// 类目等级
				categoryLevel: [{
						name: "一级类目",
						value: 0
					},
					{
						name: "二级类目",
						value: 1
					},
					{
						name: "三级类目",
						value: 2
					}
				],
				uploadPath,
				// 搜索
				searList: {
					id: undefined,
					level: undefined,
					title: undefined,
					parentId: undefined,
					pageNo: 1,
					limit: 20,
				},
				loading: false, //加载
				categoryList: [],
				total: 1, //总条数
				dialogVisible: false,
				options: [],
				parentTree: undefined,
				categoryId: undefined,
				title: '',
				categoryForm: {
					id: undefined,
					title: undefined,
					level: undefined,
					parentId: undefined,
					iconUrl: undefined,
					picUrl: undefined
				},
				categoryId: undefined,
				rules: {
					title: [{
						required: true,
						message: "类目名称不能为空",
						trigger: "blur"
					}],
				},
			}
		},
		methods: {
			//获取数据
			getData() {
				getCategoryList(this.searList).then((res) => {
					console.log(res.data.data)
					this.categoryList = res.data.data.items;
					this.total = res.data.data.total;
				})
			},
			// 获取类目树
			getCategorySpu() {
				getcategorySecondTree().then((res) => {
					this.options = this.getTreeData(res.data.data)
				})
			},
			handleSizeChange(val) { //每页条数
				this.searList.limit = val
				this.getData();
			},
			handleCurrentChange(val) { //前往第几页
				this.searList.pageNo = val
				// console.log(val)
				this.getData()
			},
			// 类目过滤
			filltterLevel(level) {
				if (this.categoryLevel[level]) {
					return this.categoryLevel[level]["name"]
				} else {
					return "错误级别"
				}
			},
			// 搜索
			search() {
				this.searList.pageNo = 1;
				var numReg = /^[0-9]*$/
				var numRe = new RegExp(numReg)
				if(this.searList.id != undefined){
					if (!numRe.test(this.searList.id)) {
						this.$message.error("请输入整数");
						return;
					}
				}
				
				this.getData()
			},
			handleLink(e) {
				if (e === undefined || e === null) {
					return;
				}
				this.searList.parentId = e[e.length - 1]
			},
			deleteCategory(data) {
				console.log(data)
				this.$confirm("此操作将永久删除该广告--" + data.fullName + "--, 是否继续?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					deleteCategory(data.value).then((res) => {
							this.$message.success("删除成功！")
							let index = this.categoryList.indexOf(data);
							this.categoryList.splice(index, 1);
							this.getCategorySpu()
						})
						.catch(() => {
							return false;
						});
				})
			},
			// 初始化表单
			fixCategory(type, value) {
				this.dialogVisible = true
				if (type === 'add') {
					this.title = "创建"
					this.categoryForm = {
						id: undefined,
						title: undefined,
						level: undefined,
						parentId: undefined,
						iconUrl: undefined,
						picUrl: undefined
					}
				} else {
					this.title = "编辑"
					this.categoryForm = Object.assign({}, {
						id: value.value,
						title: value.label,
						parentId: value.parent,
						picUrl: value.picUrl,
						iconUrl: value.iconUrl
					});
					// console.log(value.parent)
					this.categoryId = value.parent
				}
				this.getCategorySpu()
				if (this.$refs.categoryForm != undefined) {
					this.$refs.categoryForm.resetFields(); //form表单的dom渲染完在执行this.$refs.advertForm.resetFields()，去除验证
				}
			},
			// 添加
			createCategory(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						addCategory(this.categoryForm).then((res) => {
							console.log(res)
							this.dialogVisible = false;
							this.$message.success("创建成功");
							this.getData();
							this.getCategorySpu();
						})
					} else {
						return false;
					}
				})
			},
			// 编辑
			updateData(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						updateCategory(this.categoryForm).then((res) => {
							console.log(res)
							if (res.data.errno === 200) {
								this.dialogVisible = false;
								this.$message.success("更新成功");
								this.getData();
								this.getCategorySpu();
							} else {
								this.$message.error(res.data.errmsg);
							}

						})
					} else {
						return false;
					}
				})
			},
			handleLink2(e) {
				if (e == null || e === undefined) {
					return false;
				}
				if (this.title === "编辑") {
					if (this.categoryForm.id === e[e.length - 1]) {
						this.$message.error("请不要选择本节点作为父节点");
					}
				}
				this.categoryForm.parentId = e[e.length - 1];
			},
			// 关闭弹框
			closeDialog() {
				this.dialogVisible = false;
			},
			handleAvatarSuccess(res, file) {
				this.categoryForm.picUrl = URL.createObjectURL(file.raw);
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === "image/jpeg";
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error("上传头像图片只能是 JPG 格式!");
				}
				if (!isLt2M) {
					this.$message.error("上传头像图片大小不能超过 2MB!");
				}
				return isJPG && isLt2M;
			},
			// 递归
			getTreeData(data) {
				for (var i = 0; i < data.length; i++) {
					if ('children' in data[i]) {
						if (data[i].children.length < 1) {
							// children若为空数组，则将children设为undefined
							data[i].children = undefined;
						} else {
							// children若不为空数组，则继续 递归调用 本方法
							this.getTreeData(data[i].children);
						}
					}
				}
				return data;
			},
		},
		created() {
			this.getData()
			this.getCategorySpu()
		}
	}
</script>

<style>
	.category_container {
		width: 100%;
		height: 660px;
		overflow-x: auto;
		overflow-y: auto;
		padding: 20px;
	}

	.category_header>* {
		margin-left: 4px;
	}

	.category_header {
		padding-bottom: 10px;
	}
</style>
